﻿using System;
using System.Runtime.InteropServices;

namespace StockUtil
{
    public class DllHelper
    {
        [DllImport("kernel32.dll")]
        private extern static IntPtr LoadLibrary(string path);

        [DllImport("kernel32.dll")]
        private extern static bool FreeLibrary(IntPtr lib);

        [DllImport("kernel32.dll")]
        private extern static IntPtr GetProcAddress(IntPtr lib, string funcName);

        private IntPtr hModule = IntPtr.Zero;

        public bool LoadDll(String dllPath)
        {
            bool success = true;

            try
            {
                hModule = LoadLibrary(dllPath);
                if (hModule == IntPtr.Zero)
                {
                    success = false;
                }
            }
            catch
            {
                success = false;
            }

            return success;
        }

        public bool UnloadDll()
        {
            bool success = false;

            if (hModule != IntPtr.Zero)
            {
                success = FreeLibrary(hModule);
                hModule = IntPtr.Zero;
            }

            return success;
        }

        public Delegate Invoke(string funcName, Type delegateType)
        {
            if (hModule != IntPtr.Zero)
            {
                IntPtr hFunction = GetProcAddress(hModule, funcName);
                return (Delegate)Marshal.GetDelegateForFunctionPointer(hFunction, delegateType);
            }

            return null;
        }
    }
}
